import comSpSkeleton from "../../engines/components/comSpSkeleton";
import gameConfig from "../../engines/configs/gameConfig";
import O1HD, { managers, modules, services } from "../../engines/gameEngine";
import { GAME_MODE } from "../../engines/managers/gameContent/gameMode_json";
import { REWARD_TYPE } from "../../engines/services/userContent/userInterface";
import { GAME_EVENT, PAGE, TOUCH_TYPE } from "../Enum";
import { IInGamePagePrams, ILosePagePrams, INormalLevelStruct, ITipsPagePrams, IWinPagePrams } from "../Interface";
import mainRoot from "../MainRoot";

const { ccclass, property } = cc._decorator;

@ccclass
export default class NormalLevelBase extends cc.Component {
    protected levelInfo: INormalLevelStruct = null;
    protected title: string = null;
    protected tips: string = null;
    protected hadEnd: boolean = false;
    protected m_mode: GAME_MODE = GAME_MODE.NORMAL;

    onLoad() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.touchScene.bind(this));
        O1HD.on(GAME_EVENT.GAME_PAUSE, this.pauseGame.bind(this));
        O1HD.on(GAME_EVENT.GAME_RESUME, this.resumeGame.bind(this));
        O1HD.on(GAME_EVENT.ON_TIPS_GOT, this.onGetTip.bind(this));
        O1HD.on(GAME_EVENT.ON_ANSWER_GOT, this.onGetAnswer.bind(this));
    }

    
    getLevelInfo(){
        return this.levelInfo;
    }

    onGetAnswer() {

    }
    onGetTip() {

    }
    pauseGame() { }

    resumeGame() { }

    touchScene(e: cc.Event.EventTouch) {
        let pos: cc.Vec2 = e.getLocation();
        pos = this.node.convertToNodeSpaceAR(pos);
        // let node = cc.instantiate(this.md);
        // mainRoot.UIRoot.addChild(node);
        // node.setPosition(pos);
        // node.getComponent(comSpSkeleton).playAnimation("animation").start(false).onComplete(1, () => {
        //     node.removeFromParent();
        // });
    }

    async Init(info: INormalLevelStruct) {
        this.levelInfo = info;
        this.m_mode = info.mode;
        this.tips = info.tips;
        // console.warn("关卡初始化", this.levelInfo);
        let inGamePrams: IInGamePagePrams = {
            mode: this.m_mode,
            levelInfo:this.levelInfo,
            title: info.title,
            tips: info.tips,
            hideTitle: info.hideTitle
        }

        O1HD.on(GAME_EVENT.ON_BTN_TIPS, this.OnTips.bind(this));

        await mainRoot.UISystem.OpenPage(PAGE.INGAMEPAGE, inGamePrams);
    }

    protected start(): void {
        mainRoot.UISystem.ClosePage(PAGE.TIPSPAGE);
        this.scheduleOnce(() => {
            let node = this.node.getChildByName("GuangGuang");
            cc.tween(node).to(1, { opacity: 0 }).call(() => { node.active = false; }).start();
        }, 0.5);
    }

    OnTips() {
        cc.audioEngine.pauseAll();
        let rewardFun: () => void = null;
        // console.error(this.levelInfo.reward);
        if (this.levelInfo.reward) {
            rewardFun = () => {
                console.warn("!!!没有");
                if (!mainRoot.GotTips) {
                    services().userSrv.setCoins(1, true);
                    modules().uiControlModule.showGetRewarded(REWARD_TYPE.COIN, 1);
                }
            };
        }
        let tipsPrams: ITipsPagePrams = {
            mode: this.m_mode,
            levelInfo:this.levelInfo,
            tips: this.tips,
            onReward: rewardFun,
            onClose: () => {
                cc.audioEngine.resumeAll();
            }
        }
        mainRoot.UISystem.OpenPage(PAGE.TIPSPAGE, tipsPrams);
    }

    OffTouchMove(node: cc.Node, event?: cc.Node.EventType) {
        // console.log("quxiao",node.name);

        switch (event) {
            case cc.Node.EventType.TOUCH_MOVE:
                node.off(cc.Node.EventType.TOUCH_MOVE);
                break;
            case cc.Node.EventType.TOUCH_END:
            case cc.Node.EventType.TOUCH_CANCEL:
                node.off(cc.Node.EventType.TOUCH_END);
                node.off(cc.Node.EventType.TOUCH_CANCEL);
                break;
            default:
                node.off(cc.Node.EventType.TOUCH_MOVE);
                node.off(cc.Node.EventType.TOUCH_END);
                node.off(cc.Node.EventType.TOUCH_CANCEL);
                break;
        }
    }

    RegisterTouchMove(node: cc.Node, registerFun: (type: TOUCH_TYPE, outVec: cc.Vec2, deltaVec?: cc.Vec2, node?: cc.Node, event?: cc.Event.EventTouch) => void,
        releaseFun?: (event: cc.Event.EventTouch) => void) {
        let touchDir: cc.Vec2 = cc.v2();
        let touchDir1: cc.Vec2 = cc.v2();
        let lastRatio: number = 1;

        let moveFun = (event: cc.Event.EventTouch) => {
            let startDir: cc.Vec2 = null;
            let realDir: cc.Vec2 = null;
            let touches: cc.Touch[] = event.getTouches();
            // console.warn(touches.length);
            touchDir = touches[0].getLocation().sub(touches[0].getStartLocation());
            if (touches.length < 2) {
                registerFun(TOUCH_TYPE.SINGLE, touchDir, touches[0].getDelta(), node, event);
                return;
            }
            touchDir1 = touches[1].getLocation().sub(touches[1].getStartLocation());

            let cosAngle = touchDir.dot(touchDir1) / (touchDir.mag() * touchDir1.mag());
            if (cosAngle > 0.5 && cosAngle <= 1) {
                registerFun(TOUCH_TYPE.DOUBLE_SLIDER, touchDir1, touches[0].getDelta().scale(cc.v2(0.8, 0.8)), node, event);
                return;
            }

            startDir = touches[0].getStartLocation().sub(touches[1].getStartLocation());
            realDir = touches[0].getLocation().sub(touches[1].getLocation());
            let ratio = realDir.mag() / startDir.mag();
            registerFun(TOUCH_TYPE.DOUBLE_ZOOM, cc.v2(ratio, ratio), cc.v2(ratio - lastRatio, ratio - lastRatio), node, event);
            lastRatio = ratio;
        }
        let endFun = (event: cc.Event.EventTouch) => {
            lastRatio = 1;
            releaseFun && releaseFun(event);
        };
        node.on(cc.Node.EventType.TOUCH_MOVE, moveFun, this);
        node.on(cc.Node.EventType.TOUCH_END, endFun, this);
        node.on(cc.Node.EventType.TOUCH_CANCEL, endFun, this);
    }

    Win(time?: number, jyIndex?: number, userStr?: string) {
        if (this.hadEnd) { return; }
        this.hadEnd = true;

        // this.ShowObj("Xz_Zq", (node: cc.Node) => {
        //     // managers().soundMgr.playSound("huaquan");
        //     node.setPosition(position);
        // });
        // mainRoot.UISystem.ClosePage(PAGE.TIPSPAGE);
        let delayTime: number = 3.5;
        if (time) {
            delayTime = time;
        }
        this.scheduleOnce(async () => {
            mainRoot.UISystem.ClosePage(PAGE.TIPSPAGE);
            managers().soundMgr.playSound('mainSound/win');
            let winTest = null;
            // if (isUseString) {
            winTest = this.levelInfo.winText;
            // }
            if (userStr) {
                winTest = userStr;
            }
            let winPrams: IWinPagePrams = {
                mode: this.m_mode,
                levelInfo:this.levelInfo,
                winText: winTest,
                index: this.levelInfo.level,
                jyInde: jyIndex
            };
            managers().soundMgr.stopAllSound();
            await mainRoot.UISystem.OpenPage(PAGE.WINPAGE, winPrams);
            mainRoot.LevelSystem.AddLevel(this.m_mode);
            console.warn('重置1');
            mainRoot.GotTips = false;
            mainRoot.GotAnswer = false;
        }, delayTime);
    }

    Lose(time?: number) {
        if (this.hadEnd) { return; }
        this.hadEnd = true;
        let delayTime: number = 2;
        if (time) {
            delayTime = time;
        }
        // this.ShowObj("Xz_Cw", (node: cc.Node) => {
        //     if(position)
        //         node.setPosition(position);
        // });
        this.scheduleOnce(() => {
            managers().soundMgr.playSound('mainSound/inLevel');
            // let losePrams: ILosePagePrams = {
            //     mode: this.m_mode,
            //     loseText: this.levelInfo.loseText,
            //     tips: this.levelInfo.tips,
            //     index: this.levelInfo.level
            // };
            // mainRoot.UISystem.OpenPage(PAGE.LOSEPAGE, losePrams);
            mainRoot.LevelSystem.LoadLevel(mainRoot.LevelSystem.GetSignleLevelInfo(this.m_mode).bundleName, this.m_mode, null, false);
            mainRoot.UISystem.CloseAllPage();
        }, delayTime);
    }

    getHasEndGame() {
        return this.hadEnd
    }

    /**
     * 展示一个预制体到场上
     * @param name 预制体的名字，预制体需要位于GameframeBundle/Obj下
     * @param callback 加载完成回调,加载出的节点为参数
     */
    ShowObj(name: string, callback: (node: cc.Node) => void): Promise<cc.Node> {
        if (name == "Xz_Cw") {
            // managers().soundMgr.playSound("cuo");
        }
        return new Promise<cc.Node>((resolve) => {
            mainRoot.frameBundle.load(`Obj/${name}`, async (err, prefab: cc.Prefab) => {
                if (err) { console.error(err); return; }
                let node = cc.instantiate(prefab);
                if (node) {
                    this.node && (this.node.addChild(node));
                    node.scale = 0.1;
                    cc.tween(node).to(0.3, { scale: 1 }, { easing: 'backOut' }).start();
                }
                // node.setPosition(obj?obj.getPosition():cc.v2());
                // managers().soundMgr.playSound("huaquan");
                callback && (await callback(node));
                resolve(node);
            });
        });
    }

    /**
     *  更新标题
     * @param title 标题内容
     */
    reNewTiTle(title: string) {

    }

    protected onDestroy(): void {
        cc.audioEngine.stopAllEffects();
    }
}